//
//  YDYChatingTableViewController.m
//  DYChats
//
//  Created by 杨德勇 on 2016/9/12.
//  Copyright © 2016年 杨德勇. All rights reserved.
//

#import "YDYChatingTableViewController.h"
#import <GCDAsyncUdpSocket.h>
#import "SendMessageController.h"
#import "YDYMessage.h"
#import "YDYMessageTableViewCell.h"
#import "YDYNetworkTool.h"
#import <AFNetworkReachabilityManager.h>
#import <MBProgressHUD.h>
@interface YDYChatingTableViewController ()<GCDAsyncUdpSocketDelegate,UITableViewDelegate,UITableViewDataSource>
//消息展示用的tableview
@property (weak, nonatomic) IBOutlet UITableView *messageTableView;
/** 数据源 */
@property (nonatomic, strong) NSMutableArray *msgArray;
//发送消息按钮
@property (weak, nonatomic) IBOutlet UIButton *OKBtn;
//底部工具栏
@property (weak, nonatomic) IBOutlet UIView *bottomToolBarView;
//底部工具栏底部约束
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomToolBarConstraint;

//消息输入框
@property (weak, nonatomic) IBOutlet UITextField *messageTextField;
/** 记录本机IP地址和端口 */
@property (nonatomic, strong) YDYMessage *localMessage;
/** 检测网络状态 */
@property (nonatomic, strong) AFNetworkReachabilityManager *reachManager;



@end

@implementation YDYChatingTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置导航栏
    [self setupNav];
    //设置socket
    [self setupUdpSocket];
    //注册监听，键盘出现通知等
    [self setupNoti];
    //获取用户本地的局域网IP
    [self getUserIP];
    //设置tableview
    [self setupTableview];
    //监听网络
    [self setupNetwork];
    
//    [self showAlert];
}


-(void)showAlert{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"您 好" message:@"本APP需要连接WIFI或热点才可以使用（可以无网络连接）" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *act1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:act1];
    [self presentViewController:alertController animated:YES completion:nil];
    
    self.messageTextField.enabled = NO;
}


-(void)setupNetwork{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    self.reachManager = manager;
    
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: // 未知网络
                YDYLog(@"未知网络");
                self.messageTextField.enabled = YES;
                break;
                
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
                [self showAlert];
                YDYLog(@"没有网络(断网)");
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
                YDYLog(@"手机自带网络");
                [self showAlert];
                
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
                YDYLog(@"WIFI");
                self.messageTextField.enabled = YES;
                break;
        }
    }];
    [manager startMonitoring];
    
}

-(void)setupTableview{
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.messageTableView.backgroundColor = [UIColor colorWithRed:235/255 green:235/255 blue:235/255 alpha:0];
}
-(void)setupNoti{
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardChanged:) name:UIKeyboardWillChangeFrameNotification object:nil];
}


-(void)setupNav{
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"发送" style:UIBarButtonItemStylePlain target:self action:@selector(jumpsendMessageController)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"发送" style:UIBarButtonItemStylePlain target:self action:@selector(OKBtnDidClick:)];
    
}

-(void)setupUdpSocket{
    dispatch_queue_t dqueue = dispatch_queue_create("socket queue", NULL);
    
    self.udpServeSocket = [[GCDAsyncUdpSocket alloc]initWithDelegate:self delegateQueue:dqueue];
    //等待12345端口的消息
    [self.udpServeSocket bindToPort:ydy_port error:nil];
    [self.udpServeSocket joinMulticastGroup:ydy_host error:nil];
    [self.udpServeSocket beginReceiving:nil];
    
    //只接受一次信息
//    [self.udpServeSocket receiveOnce:nil];
    
    
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [self.udpServeSocket close];
    self.udpServeSocket = nil;
    
    [self.reachManager stopMonitoring];
}
#pragma mark -
#pragma mark -控件监听
- (IBAction)OKBtnDidClick:(UIButton *)sender {
//    [self checkNetWork];
    if (self.messageTextField.text.length==0)return;
        
    
//    [self.messageTextField resignFirstResponder];
    
    
    YDYMessage *message = [[YDYMessage alloc]init];
    message.msgString = self.messageTextField.text;
    message.creat_at = [NSDate date];
    
    [self.udpServeSocket sendData:message.msgData toHost:message.ip port:message.port withTimeout:60 tag:100];
    
//    [self.udpServeSocket sendData:message.msgData toHost:@"224.0.0.1" port:4333 withTimeout:60 tag:100];

    [self.messageTableView reloadData];
    
    self.messageTextField.text = @"";
    
}
- (IBAction)clearBtnDidClick:(UIButton *)sender {
    [self.msgArray removeAllObjects];
    [self.messageTableView reloadData];
}
- (IBAction)textHasChange:(UITextField *)sender {
    self.OKBtn.enabled = sender.hasText;
}

#pragma mark -
#pragma mark -私有方法
-(void)keyBoardChanged:(NSNotification *)note{
    //获取键盘弹出或收回时frame
    CGRect keyboardFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    //获取键盘弹出所需时长
    float duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
  
    //添加弹出动画
    [UIView animateWithDuration:duration animations:^{
         self.bottomToolBarView.transform = CGAffineTransformMakeTranslation(0, keyboardFrame.origin.y - self.view.frame.size.height);
    }];
}

-(void)jumpsendMessageController{
    
    SendMessageController *chatingVC = [[SendMessageController alloc]init];
    
    [self.navigationController pushViewController:chatingVC animated:YES];
    
    
}
-(void)getUserIP{
    NSDictionary *dict =[YDYNetworkTool getIPAddresses];
    
    
    NSString *ip;
    if(TARGET_IPHONE_SIMULATOR){
        ip =  dict[@"en1/ipv4"];
    }else{
        ip = [YDYNetworkTool getIPAddress:YES];
    }
    
    
    self.localMessage.ip = ip;
    
}
#pragma mark -
#pragma mark -asyncUdpDelegate

-(void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext{
    
    
    YDYMessage *message = [[YDYMessage alloc]init];
    message.ip = [GCDAsyncUdpSocket hostFromAddress:address];
    message.port = [GCDAsyncUdpSocket portFromAddress:address];
    message.msgData = data;
    message.creat_at = [NSDate date];
   
    
    
    YDYLog(@"ip:%@,port:%hu,localip:%@",message.ip,message.port,self.localMessage.ip);
    
    [self.msgArray addObject:message];
    
    dispatch_sync(dispatch_get_main_queue(), ^{
        [self.messageTableView reloadData];
       
        [self.messageTableView scrollToRowAtIndexPath: [NSIndexPath indexPathForRow:self.msgArray.count-1 inSection:0] atScrollPosition:0 animated:YES];
    });
    
    
    
}


-(void)udpSocket:(GCDAsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error{
    YDYLog(@"ydy- 没有发送成功,%@",error);
}
-(void)udpSocket:(GCDAsyncUdpSocket *)sock didSendDataWithTag:(long)tag{
    YDYLog(@"成功发送一条消息");
    
}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.msgArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YDYMessage *message = self.msgArray[indexPath.row];
    NSString *identifier;
    if ([message.ip isEqualToString:self.localMessage.ip]) {
        identifier = @"me";
    }else{
        identifier = @"other";
    }
    
    YDYMessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    cell.text = message.msgString;
    return cell;
}


#pragma mark -
#pragma mark -tableviewdelegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.messageTextField resignFirstResponder];
}


#pragma mark -
#pragma mark -懒加载
-(NSMutableArray *)msgArray{
    if (_msgArray == nil) {
        _msgArray = [NSMutableArray array];
        YDYMessage *message = [[YDYMessage alloc]init];
        message.msgString = @"泥吼啊";
        [_msgArray addObject:message];
        
        
    }
    return _msgArray;
}
-(YDYMessage *)localMessage{
    if (_localMessage == nil) {
        _localMessage = [[YDYMessage alloc]init];
    }
    return _localMessage;
}
@end
